package com.cneport.das.client.conf;

import com.cneport.das.common.utils.FileUtil;
import com.cneport.das.common.utils.JAXBUtils;
import com.cneport.das.common.utils.StringUtil;
import com.cneport.das.common.validate.FieldCheckUtil;
import com.cneport.das.common.validate.ResultVO;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Desc 客户端配置文件缓存
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2021-12-16 17:23:28
 */
@Configuration
@Slf4j
@Getter
public class ClientConfCache {

    @Value("${das.client.confBasePath}")
    private String basePath;
    @Value("${das.client.serverService.url}")
    private String serverServiceUrl;
    @Value("${das.client.clientService.url}")
    private String clientServiceUrl;

    private final String TRANS_PREFIX = "trans-";
    private final String FILE_PREFIX = "file-";
    private final String MQ_PREFIX = "mq-";
    private final String APPENDIX = ".xml";
    private final String PRI = "pri";

    private final static Map<String, TransConf> transConf = new ConcurrentHashMap<>();
    private final static Map<String, FileConf> fileConf = new ConcurrentHashMap<>();
    private final static Map<String, MqConf> mqConf = new ConcurrentHashMap<>();
    private final static Set<String> corpNos = Collections.synchronizedSet(new HashSet<>());

    @Scheduled(cron = "0 0/3 * * * ?")
    public void refresh() {
        parseConf();
        log.info("刷新配置!");
    }

    @PostConstruct
    public void parseConf() {
        String baseConf = basePath;
        File file = new File(baseConf);
        if (!file.exists()) {
            log.error("没有客户端配置");
            return;
        } else {
            String[] fileNames = file.list();
            if (fileNames != null && fileNames.length > 0) {
                for (String corpNo : fileNames) {
                    corpNos.add(corpNo);
                    //分析配置文件：tans-corpNo.xml
                    String transFileName = baseConf + File.separator + corpNo + File.separator + TRANS_PREFIX + corpNo + APPENDIX;
                    File confFile = new File(transFileName);
                    if (confFile.exists()) {
                        String content = FileUtil.readFile(transFileName);
                        if (!StringUtil.isBlank(content)) {
                            TransConf dc = JAXBUtils.xml2Obj(TransConf.class, content);
                            if (dc != null) {
                                ResultVO vo = FieldCheckUtil.validate(dc, null);
                                if (!vo.isSuccess()) {
                                    log.error(vo.getErrorStr());
                                } else {
                                    transConf.put(corpNo, dc);
                                }
                            }
                        }
                    }
                    //分析配置文件：file-corpNo.xml
                    String fileFileName = baseConf + File.separator + corpNo + File.separator + FILE_PREFIX + corpNo + APPENDIX;
                    File fileConfFile = new File(fileFileName);
                    if (fileConfFile.exists()) {
                        String content = FileUtil.readFile(fileFileName);
                        if (!StringUtil.isBlank(content)) {
                            FileConf fc = JAXBUtils.xml2Obj(FileConf.class, content);
                            if (fc != null) {
                                ResultVO vo = FieldCheckUtil.validate(fc, null);
                                if (!vo.isSuccess()) {
                                    log.error(vo.getErrorStr());
                                } else {
                                    fileConf.put(corpNo, fc);
                                }
                            }
                        }
                    }

                    //分析配置文件：file-corpNo.xml
                    String mqFileName = baseConf + File.separator + corpNo + File.separator + FILE_PREFIX + corpNo + APPENDIX;
                    File mqConfFile = new File(mqFileName);
                    if (mqConfFile.exists()) {
                        String content = FileUtil.readFile(mqFileName);
                        if (!StringUtil.isBlank(content)) {
                            MqConf mc = JAXBUtils.xml2Obj(MqConf.class, content);
                            if (mc != null) {
                                ResultVO vo = FieldCheckUtil.validate(mc, null);
                                if (!vo.isSuccess()) {
                                    log.error(vo.getErrorStr());
                                } else {
                                    mqConf.put(corpNo, mc);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public TransConf getTransConfigByCorpNo(String copNo) {
        TransConf dasClient = transConf.get(copNo);
        return dasClient;
    }

    public FileConf getFileConfigByCorpNo(String copNo) {
        FileConf dasClient = fileConf.get(copNo);
        return dasClient;
    }

    public MqConf getMqConfigByCorpNo(String copNo) {
        MqConf dasClient = mqConf.get(copNo);
        return dasClient;
    }

    public String getPriEncoderPath(String copNo) {
        final String pemDir = "pem";
        TransConf tc = transConf.get(copNo);
        if (tc != null) {
            String encoderVer = StringUtil.isBlank(tc.getEncoderVer()) ? "1.0" : tc.getEncoderVer();
            String priDir = basePath + File.separator + copNo + File.separator + pemDir + File.separator;
            String keyName = copNo + "_" + encoderVer + "_PRI.pem";
            String path = priDir + keyName;
            File fl = new File(path);
            if (fl.exists()) {
                return path;
            }
        }
        return "";
    }

    public Set<String> getAllCorpNo() {
        return corpNos;
    }
}
